package com.guguju.ssms.feature.me;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;

import com.blankj.utilcode.utils.SPUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.JsonObject;
import com.guguju.ssms.Guguju;
import com.guguju.ssms.R;
import com.guguju.ssms.bean.UserInfo;
import com.guguju.ssms.bean.UserInfoData;
import com.guguju.ssms.constant.IntentParms;
import com.guguju.ssms.constant.SPConstant;
import com.guguju.ssms.constant.UrlConstant;
import com.guguju.ssms.core.base.BaseFragment;
import com.guguju.ssms.core.http.BaseResponse;
import com.guguju.ssms.core.http.HttpLoader;
import com.guguju.ssms.core.http.JsonCallback;
import com.guguju.ssms.core.log.LogUtil;
import com.guguju.ssms.feature.Home.HomeActivity;
import com.guguju.ssms.feature.Html.HtmlActivity;
import com.guguju.ssms.feature.login.LoginActivity;

import okhttp3.Call;
import okhttp3.Response;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;


/**
 * Created by dell on 2022-5-14.
 */
public class MeFragment  extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    /**
     * fragment name
     */
    public static final String TAG = MeFragment.class.getName();
    RecyclerView rvHome;
    SwipeRefreshLayout swipeRefreshLayout;
    private HomeActivity activity;
    private MeAdapter adapter;
    private HeaderViewHolder headerViewHolder;





    //ImageView ivHeader;
   // ImageView ivMsg;
   // ImageView ivAvatar;
   // TextView tvStoreName;
    //LinearLayout llUserLevel;

    private ArrayList<UserInfo> moudleData = new ArrayList<>();

    /**
     * 使用静态工厂方法newInstance(...)来获取Fragment实例
     *
     * @return fragment instance
     */
    public static MeFragment newInstance() {
        LogUtil.i(TAG + "   create");
        Bundle args = new Bundle();
        MeFragment meFragment = new MeFragment();
        meFragment.setArguments(args);
        return meFragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_me;
    }

    @Override
    protected void afterCreate() {
        activity = (HomeActivity) getActivity();
        swipeRefreshLayout = getView().findViewById(R.id.srl_home);



        rvHome= getView().findViewById(R.id.rv_home);
        if(Guguju.USERID<=0) {
            if (!Guguju.isOpenLoginActivity) {
                Guguju.isOpenLoginActivity = true;
                if (Guguju.applicationContext != null) {
                    Intent intent = new Intent(Guguju.applicationContext, LoginActivity.class);
                    intent.putExtra(IntentParms.LOGIN_FROM, IntentParms.LOGIN_FROM_HTTPLOAD);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    Guguju.applicationContext.startActivity(intent);
                }
            }
        }


        //ivHeader =  getView().findViewById(R.id.iv_me_header);
       // ivMsg =  getView().findViewById(R.id.iv_me_msg);
       // ivAvatar =  getView().findViewById(R.id.iv_me_avatar);
       // tvStoreName =  getView().findViewById(R.id.tv_me_store_name);
      //  llUserLevel =  getView().findViewById(R.id.ll_me_user_level);
       // swipeRefreshLayout.setOnRefreshListener(this);
     //   getUserData();



      adapter = new MeAdapter(getContext(), moudleData);
        GridLayoutManager layoutManager = new GridLayoutManager(getActivity(),3);
        rvHome.setLayoutManager(layoutManager);
        rvHome.setAdapter(adapter);
        View headerView = View.inflate(getActivity(), R.layout.header_me_fragment, null);
        headerViewHolder = new HeaderViewHolder(headerView);
        adapter.addHeaderView(headerView);
        swipeRefreshLayout.setOnRefreshListener(this);
        getUserData();
    }

    /**
     * 获取用户数据
     */
    private void getUserData() {
        JsonObject params = new JsonObject();
        params.addProperty("userId", Guguju.USERID);
        params.addProperty("auth", TextUtils.isEmpty(Guguju.AUTH) ? "" : Guguju.AUTH);
        params.addProperty("asessToken", TextUtils.isEmpty(Guguju.ASESSTOKEN) ? "" : Guguju.ASESSTOKEN);
       // Guguju.applicationContext=getContext();
        HttpLoader.post(UrlConstant.GET_USERINFO, params, true, new JsonCallback<BaseResponse<UserInfoData>>() {
            @Override
            public void onSuccess(BaseResponse<UserInfoData> userInfoData, Call call, Response response) {
                swipeRefreshLayout.setRefreshing(false);
                if (userInfoData != null && userInfoData.data != null) {
                    setUserData(userInfoData.data.getUserInfo());
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                swipeRefreshLayout.setRefreshing(false);
                super.onError(call, response, e);
            }
        });
    }


    /**
     * 设置用户数据
     */
    private void setUserData(@NonNull final UserInfo userInfo) {
        if (userInfo != null) {

            headerViewHolder.tvStoreName.setText("昵称:"+ userInfo.getShowName());
            headerViewHolder.tvShopTrade.setText("登录名:"+userInfo.getLogonName()+"  ");
            headerViewHolder.tvEmail.setText("邮箱地址:"+userInfo.getEmail());
            headerViewHolder.tvPrositionType.setText("岗位:"+userInfo.getRegTypeName());

            //adapter.notifyDataSetChanged();
        }

    }


    /**
     * Called when a swipe gesture triggers a refresh.
     */
    @Override
    public void onRefresh() {
        getUserData();
    }


    class HeaderViewHolder {

        ImageView ivMsg;
        //ImageView ivAvatar;
        TextView tvStoreName;
        TextView tvEmail;
        TextView tvPrositionType;
        ImageView ivHeader;
        Button btnuserLayout;
       LinearLayout llhealthmonitor;

        //@BindView(R.id.iv_me_share_store)
        //ImageView ivShareStore;
       // @BindView(R.id.tv_home_store_change)
        //TextView tvStoreChange;

        TextView tvShopTrade;
        /**
         * scheme和registrationID的sp存储
         */
        private SPUtils schemeSp;

        HeaderViewHolder(View view) {
            ivMsg=view.findViewById(R.id.iv_home_msg);
            btnuserLayout=view.findViewById(R.id.bt_user_layout);
            //ivAvatar=view.findViewById(R.id.iv_home_avatar);
            tvStoreName=view.findViewById(R.id.tv_home_store_name);
            tvEmail=view.findViewById(R.id.tv_home_email);
            tvPrositionType=view.findViewById(R.id.tv_PrositionType);
            llhealthmonitor=view.findViewById(R.id.ll_mehealthmonitor);


            ivHeader=view.findViewById(R.id.iv_home_header);
            //llUserLevel=view.findViewById(R.id.ll_home_user_level);

            tvShopTrade=view.findViewById(R.id.tv_home_shop_trade);

            ivMsg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToastUtils.showShortToast(getActivity(), "未开发预留，功能有点多", Toast.LENGTH_LONG);
                }
            });

            btnuserLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Guguju.USERID = 0;
                    Guguju.AUTH = "";
                    Guguju.ASESSTOKEN ="";
                    if (schemeSp == null) {
                        schemeSp = new SPUtils(getActivity(), SPConstant.SP_XML_NAME);
                    }
                    schemeSp.putInt(SPConstant.USERID, 0);
                    schemeSp.putString(SPConstant.AUTH, "");
                    schemeSp.putString(SPConstant.ASESSTOKEN,"");
                    Intent intent = new Intent(getActivity(), LoginActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }
            });


            llhealthmonitor.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent htmlIntent = new Intent(getActivity(), HtmlActivity.class);
                    htmlIntent.putExtra(IntentParms.HTML5_URL, UrlConstant.USER_HEALTHMONITOR_H5);
                    startActivity(htmlIntent);
                }
            });
        }

    }

}